<?php

namespace app\api\controller;

use Easywechat\MiniApp\Application;

use Throwable;
use app\common\controller\Frontend;
use app\admin\model\Health;
use app\admin\model\User;
use app\admin\model\Datalist;
use app\admin\controller\Liliao;

class Mpwechat extends Frontend{
    private $mpWecaht;
    public function initialize(): void
    {
        parent::initialize();
        $this->mpWecaht = new Application([
            'app_id' => 'wxede4761cc940683c',
            'secret' => '78be88374030f567e8135101ca4d6e9d',
            'response_type' => 'array'
        ]);
    }

    public function sessioncode($code){
        $utils = $this->mpWecaht->getUtils();
        $response = $utils->codeToSession($code);
        $response['openid'];
        $user = User::where('openid',$response['openid'])->find();
        if(!$user){
            $user = new User();
            $user->save([
                'openid' => $response['openid']
            ]);
        }
        if($user->is_verify == 1){
            $this->auth->direct($user->id);
            $data['openid'] = $response['openid'];
            $data['userinfo']['username'] = $user->username;
            $data['userinfo']['avatar'] = $user->avatar;
            $data['userinfo']['token'] = $this->auth->getToken();
            $data['userinfo']['health'] = Health::where('user_id',$user->id)->find() || [];
            
        }else{
            
            $data['openid'] = $response['openid'];
        }
        $this->success('登录成功',$data);
    }
    public function login(){
        if($this->request->isPost()){
            $openid = $this->request->param('openid');
            $avatar = $this->request->param('avatar');
            $user = User::where('openid',$openid)->find();
            $user->avatar = $avatar;
            $user->is_verify = 1;
            $user->save();
            $this->auth->direct($user->id);
            $data['userinfo']['username'] = $user->username;
            $data['userinfo']['avatar'] = $user->avatar;
            $data['userinfo']['token'] = $this->auth->getToken();
            $data['userinfo']['health'] = Health::where('user_id',$user->id)->find();
            $this->success('登录成功',$data);
        }
    }
    public function index()
    {
        

    }
    
}        